let multer=require('multer');
let Duplex = require('stream').Duplex;
let fs = require('fs');
let paramsUtil = require('./daoUtil');
let strateries = {
    disk : multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, process.cwd())
        },
        filename: function (req, file, cb) {
            var userinfo = req.session && req.session.userinfo;
            cb(null, [(userinfo && userinfo.name) || file.fieldname, Date.now(), file.originalname].join('-'));
        }
    }),
    memory : multer.memoryStorage()
};

let getInstance = function (strategy) {
    //创建实例
    let instance = multer({storage: strateries[strategy]});
    instance.strategy = strategy;
    //单文件上传
    instance.uploadSingleFile = function (req,res,fileName,cb,validateRule) {
        let resolver = instance.single(fileName);
        resolver(req, res, function (err) {
            let file = req.file;
            if (!err && paramsUtil.isArray(validateRule)){
                let validator = paramsUtil.validate(validateRule,req.body);
                if (!validator.valid){
                    err = validator.error;
                    if (file && instance.strategy==='disk'){
                        instance.deleteFileFromDisk(file.path);
                        file = null;
                    }
                }
            }
            cb(err, req.body, file);
        });
    }
    //删除本地文件/文件夹
    instance.deleteFileFromDisk = function (path) {
        if(fs.existsSync(path)) {
            if (fs.statSync(path).isDirectory()){
                var files = [];
                files = fs.readdirSync(path);
                files.forEach(function(file,index){
                    var curPath = path + "/" + file;
                    if(fs.statSync(curPath).isDirectory()) {
                        deleteFolderRecursive(curPath);
                    } else {
                        fs.unlinkSync(curPath);
                    }
                });
                fs.rmdirSync(path);
            }else{
                fs.unlinkSync(path);
            }
        }
    }
    //根据本地路径获取文件流
    instance.getFileAsStream = function (path) {
        if(fs.existsSync(path)) {
            return fs.createReadStream(path);
        }else{
            return null;
        }
    }
    //将Buffer转换为流
    instance.getStreamFromBuffer = function(buffer){
        var stream = new Duplex();
        stream.push(buffer);
        stream.push(null);
        return stream;
    }
    return instance;
}

module.exports = function (uploadStrategy) {
    return getInstance('memory'===uploadStrategy?uploadStrategy:'disk');
};